/**
 * 首页-模板数据
 */
 const RxfileWrite = require('rxfile-write')
const { router, libQuery } = require('../../lib/route')
const pathJoin = require('../common-api/data-path')

libQuery((req, res, next, method) => {
  // console.log('req=', req)

  // const headers = req.headers || {}
  // let host = headers.host || '/'
  // host = 'http://' + host

  const cookies = req.cookies
  const user = cookies.user || ''
  // console.log('cookies=', cookies)
  if (!user) {
    res.type('html')
    res.renderError('当前用户没有登录')
    return
  }

  getUserInfo(user).then(data => {
    res.send(JSON.stringify(data))
  }).then(error => {
    res.renderError(error.message || '')
  })
}, '/customerdetail')

module.exports = router

function getUserInfo(user) {
  const userPath = pathJoin('customerdetail/' + user + '.js')
  return new Promise((resolve, reject) => {
    RxfileWrite.exists(userPath).then(() => {
      const data = require(userPath)
      resolve(data)
    }).catch(() => {
      const commontDetail = pathJoin('customerdetail/0.js')
      RxfileWrite.exists(commontDetail).then(() => {
        const data = require(commontDetail)
        resolve(data)
      }).catch(() => {
        reject(new Error('unknow'))
      })
    })
  })
}